<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { wallpaperCategoriesPage, sendCategories } from '@/api/index.js'
import { getSmartPageNumbers, getEllipsisStatus } from '@/utils/pagination.js'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const imageList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(21) // 每页21张图片，一行3张
const failedImages = ref(new Set()) // 记录加载失败的图片ID

// 筛选条件
const filterForm = reactive({
  type: 1, // 类型：1-静态壁纸，2-动态壁纸，默认静态
  heat: 1, // 热度：1-最热，2-最新，默认最热
  categories: null // 分类ID，默认不选
})

// 分类列表
const categories = ref([])

// 筛选选项
const typeOptions = [
  { label: '静态', value: 1 },
  { label: '动态', value: 2 }
]

const heatOptions = [
  { label: '最热', value: 1 },
  { label: '最新', value: 2 }
]

// 获取分类列表
const getCategories = async () => {
  try {
    const response = await sendCategories()
    if (response.code === 200) {
      categories.value = response.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 测试数据
const mockImages = [
  {
    id: 1,
    name: '科技未来城市',
    url: 'https://images.unsplash.com/photo-1518709268805-4e9042af2176?w=400&h=300&fit=crop',
    category: '科技',
    resolution: '4K',
    ratio: '16:9'
  },
  {
    id: 2,
    name: '动漫少女',
    url: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=300&fit=crop',
    category: '动漫',
    resolution: '2K',
    ratio: '4:3'
  },
  {
    id: 3,
    name: '自然风景',
    url: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=300&fit=crop',
    category: '风景',
    resolution: '1080P',
    ratio: '16:9'
  },
  {
    id: 4,
    name: '人物肖像',
    url: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400&h=300&fit=crop',
    category: '人物',
    resolution: '4K',
    ratio: '1:1'
  },
  {
    id: 5,
    name: '可爱动物',
    url: 'https://images.unsplash.com/photo-1543852786-1cf6624b998d?w=400&h=300&fit=crop',
    category: '动物',
    resolution: '2K',
    ratio: '16:9'
  },
  {
    id: 6,
    name: '抽象艺术',
    url: 'https://images.unsplash.com/photo-1541961017774-22349e4a1262?w=400&h=300&fit=crop',
    category: '科技',
    resolution: '4K',
    ratio: '21:9'
  },
  {
    id: 7,
    name: '星空夜景',
    url: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=300&fit=crop',
    category: '风景',
    resolution: '1080P',
    ratio: '16:9'
  },
  {
    id: 8,
    name: '机械战士',
    url: 'https://images.unsplash.com/photo-1518709268805-4e9042af2176?w=400&h=300&fit=crop',
    category: '科技',
    resolution: '2K',
    ratio: '4:3'
  },
  {
    id: 9,
    name: '卡通角色',
    url: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=300&fit=crop',
    category: '动漫',
    resolution: '720P',
    ratio: '1:1'
  },
  {
    id: 10,
    name: '城市夜景',
    url: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=300&fit=crop',
    category: '风景',
    resolution: '4K',
    ratio: '16:9'
  },
  {
    id: 11,
    name: '科幻飞船',
    url: 'https://images.unsplash.com/photo-1518709268805-4e9042af2176?w=400&h=300&fit=crop',
    category: '科技',
    resolution: '2K',
    ratio: '21:9'
  },
  {
    id: 12,
    name: '美丽花朵',
    url: 'https://images.unsplash.com/photo-1541961017774-22349e4a1262?w=400&h=300&fit=crop',
    category: '风景',
    resolution: '1080P',
    ratio: '4:3'
  }
]

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value)
})

// 计算分页显示的页码
const visiblePages = computed(() => {
  return getSmartPageNumbers(currentPage.value, totalPages.value, 5)
})

// 计算省略号状态
const ellipsisStatus = computed(() => {
  return getEllipsisStatus(currentPage.value, totalPages.value, visiblePages.value)
})

// 获取图片列表
const fetchImageList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      type: filterForm.type,
      heat: filterForm.heat
    }

    // 只有当分类ID存在时才添加到请求参数中
    if (filterForm.categories) {
      params.categories = filterForm.categories
    }

    const response = await wallpaperCategoriesPage(params)
    if (response.code === 200) {
      imageList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      console.error('获取图片列表失败:', response.msg)
    }
  } catch (error) {
    console.error('获取图片列表出错:', error)
  } finally {
    loading.value = false
  }
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.type = 1
  filterForm.heat = 1
  filterForm.categories = null
  currentPage.value = 1
  failedImages.value.clear() // 清空失败图片记录
  fetchImageList()
  // 滚动到页面顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 处理筛选条件变化
const handleFilterChange = () => {
  currentPage.value = 1
  failedImages.value.clear() // 清空失败图片记录
  fetchImageList()
  // 滚动到页面顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    fetchImageList()
    // 滚动到页面顶部
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

// 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    fetchImageList()
    // 滚动到页面顶部
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

// 跳转到指定页
const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    fetchImageList()
    // 滚动到页面顶部
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

// 处理图片点击
const handleImageClick = (image) => {
  router.push(`/wallpaper/${image.id}`)
}



// 处理图片加载失败
const handleImageError = (imageId) => {
  failedImages.value.add(imageId)
}

// 组件挂载时获取数据
onMounted(() => {
  getCategories()
  fetchImageList()
})
</script>

<template>
  <div class="classification-query">
    <!-- 筛选条件区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <!-- 类型 -->
        <div class="filter-item">
          <label class="filter-label">类型</label>
          <select v-model="filterForm.type" @change="handleFilterChange" class="filter-select">
            <option v-for="option in typeOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
        </div>

        <!-- 排序 -->
        <div class="filter-item">
          <label class="filter-label">排序</label>
          <select v-model="filterForm.heat" @change="handleFilterChange" class="filter-select">
            <option v-for="option in heatOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
        </div>

        <!-- 分类 -->
        <div class="filter-item">
          <label class="filter-label">分类</label>
          <select v-model="filterForm.categories" @change="handleFilterChange" class="filter-select">
            <option :value="null">请选择分类</option>
            <option v-for="category in categories" :key="category.id" :value="category.id">
              {{ category.category_name }}
            </option>
          </select>
        </div>

        <!-- 操作按钮 -->
        <div class="filter-actions">
          <button @click="resetFilter" class="btn btn-secondary">重置</button>
        </div>
      </div>
    </div>

    <!-- 图片展示区域 -->
    <div class="image-section">
      <h3 class="section-title">
        分类壁纸
      </h3>
      
      <div v-if="loading" class="loading">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      
      <div v-else-if="imageList.length === 0" class="empty-state">
        <p>暂无数据</p>
      </div>
      
      <div v-else class="image-grid">
        <div 
          v-for="image in imageList" 
          :key="image.id" 
          class="image-item"
          @click="handleImageClick(image)"
          v-show="!failedImages.has(image.id)"
        >
          <div class="image-container">
            <img 
              :src="image.url" 
              :alt="image.name"
              class="image"
              @error="handleImageError(image.id)"
            />
            <div class="image-overlay">
              <div class="image-info">
                <h3 class="image-title">{{ image.name }}</h3>
                <div class="image-details">
                  <span class="image-category">{{ image.classify || '未分类' }}</span>
                  <span class="image-resolution">{{ image.type === 1 ? '静态' : '动态' }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页区域 -->
    <div v-if="total > 0" class="pagination-section">
      <div class="pagination">
        <button 
          @click="prevPage" 
          :disabled="currentPage <= 1"
          class="pagination-btn"
          :class="{ disabled: currentPage <= 1 }"
        >
          上一页
        </button>
        
        <div class="page-numbers">
          <!-- 第一页按钮 -->
          <button
            v-if="ellipsisStatus.showStart"
            @click="goToPage(1)"
            class="page-btn"
            :class="{ active: currentPage === 1 }"
          >
            1
          </button>
          
          <!-- 前省略号 -->
          <span v-if="ellipsisStatus.showStart" class="page-ellipsis">...</span>
          
          <!-- 页码按钮 -->
          <button 
            v-for="page in visiblePages" 
            :key="page"
            @click="goToPage(page)"
            class="page-btn"
            :class="{ active: currentPage === page }"
          >
            {{ page }}
          </button>
          
          <!-- 后省略号 -->
          <span v-if="ellipsisStatus.showEnd" class="page-ellipsis">...</span>
          
          <!-- 最后一页按钮 -->
          <button
            v-if="ellipsisStatus.showEnd"
            @click="goToPage(totalPages)"
            class="page-btn"
            :class="{ active: currentPage === totalPages }"
          >
            {{ totalPages }}
          </button>
        </div>
        
        <button 
          @click="nextPage" 
          :disabled="currentPage >= totalPages"
          class="pagination-btn"
          :class="{ disabled: currentPage >= totalPages }"
        >
          下一页
        </button>
      </div>
      
      <div class="pagination-info">
        第 {{ currentPage }} 页，共 {{ totalPages }} 页，总计 {{ total }} 张图片
      </div>
    </div>
  </div>
</template>

<style scoped>
.classification-query {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0;
}

/* 筛选区域样式 */
.filter-section {
  background: #fff;
  border-radius: 12px;
  padding: 20px 20px;
  margin: 0 30px 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.filter-row {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  margin-bottom: 20px;
  align-items: flex-end;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 140px;
}

.filter-actions {
  display: flex;
  gap: 12px;
  margin-left: auto;
}

.filter-label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin: 0;
}

.filter-select {
  padding: 10px 12px;
  border: 1px solid #e1e5e9;
  border-radius: 8px;
  font-size: 14px;
  color: #333;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  appearance: none;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
  background-position: right 8px center;
  background-repeat: no-repeat;
  background-size: 16px;
  padding-right: 32px;
}

.filter-select:hover {
  border-color: #3b82f6;
}

.filter-select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}



.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-primary {
  background: #3b82f6;
  color: #fff;
}

.btn-primary:hover {
  background: #2563eb;
  transform: translateY(-1px);
}

.btn-secondary {
  background: #f3f4f6;
  color: #374151;
  border: 1px solid #d1d5db;
}

.btn-secondary:hover {
  background: #e5e7eb;
  transform: translateY(-1px);
}

/* 图片展示区域样式 */
.image-section {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 12px;
  margin: 0 30px 20px;
  padding: 30px 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

  .section-title {
    font-size: 28px;
    font-weight: 600;
    margin-bottom: 40px;
    text-align: center;
    color: #2c3e50;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;

    &::after {
      content: '';
      position: absolute;
      bottom: -8px;
      left: 50%;
      transform: translateX(-50%);
      width: 60px;
      height: 3px;
      background: linear-gradient(90deg, #3498db, #2ecc71);
      border-radius: 2px;
    }
  }
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
  font-size: 16px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  max-width: 1250px;
  margin: 0 auto;
}

.image-item {
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

.image-item:hover {
  transform: translateY(-8px) scale(1.02);
}

.image-container {
  position: relative;
  width: 100%;
  height: 280px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  background: #f8fafc;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.image-item:hover .image-container {
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.25);
}

.image-item:hover .image {
  transform: scale(1.05);
}

.image-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
  padding: 20px;
  color: #fff;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-item:hover .image-overlay {
  opacity: 1;
}

.image-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.image-details {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.image-category,
.image-resolution,
.image-ratio {
  font-size: 12px;
  padding: 2px 6px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  backdrop-filter: blur(4px);
}

/* 分页区域样式 */
.pagination-section {
  background: #fff;
  border-radius: 12px;
  padding: 30px 20px;
  margin: 0 30px 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 16px;
}

.pagination-btn {
  padding: 10px 16px;
  border: 1px solid #d1d5db;
  background: #fff;
  color: #374151;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.pagination-btn:hover:not(.disabled) {
  border-color: #3b82f6;
  color: #3b82f6;
  transform: translateY(-1px);
}

.pagination-btn.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-numbers {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-btn {
  width: 40px;
  height: 40px;
  border: 1px solid #d1d5db;
  background: #fff;
  color: #374151;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
}

.page-btn:hover {
  border-color: #3b82f6;
  color: #3b82f6;
  transform: translateY(-1px);
}

.page-btn.active {
  background: #3b82f6;
  border-color: #3b82f6;
  color: #fff;
}

.page-ellipsis {
  padding: 8px 12px;
  color: #666;
  font-weight: 500;
}

.pagination-info {
  text-align: center;
  color: #6b7280;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .filter-row {
    gap: 16px;
  }
  
  .filter-item {
    min-width: 120px;
  }
  
  .image-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .classification-query {
    padding: 16px;
  }
  
  .filter-row {
    flex-direction: column;
    gap: 16px;
  }
  
  .filter-item {
    min-width: auto;
  }
  
  .image-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .image-container {
    height: 240px;
  }
  
  .pagination {
    flex-direction: column;
    gap: 16px;
  }
}

@media (max-width: 480px) {
  .filter-actions {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }
}
</style>